from django.shortcuts import render, redirect, HttpResponse
from django.contrib.sessions.models import Session
from .models import *
import pymysql
import os
import json
import threading

lock = threading.Lock()

# Create your views here.
# 创建MySQL连接
mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8mb4')
cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)


# 重连数据库装饰器
def ping_mysql():
    mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8mb4')
    cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)

    return mysql_conn, cursor


# 注册账号
def regist_user(request):
    '''

    :param request: username,email,password
    :return:code:是否注册成功
            text:文本提示
    '''

    result = {
        "code": 0,
        "text": "注册成功"
    }

    # 从请求中获取用户注册信息
    username = request.POST.get('username')
    name = request.POST.get('name')
    email = request.POST.get('email')
    password = request.POST.get('password')

    # 判断用户名是否存在
    user_result = T_user.objects.filter(username=username)
    # print(user_result)
    if user_result.exists():
        result["code"] = -1
        result["text"] = "用户名已存在，请重新输入"
    else:
        # 将注册用户信息填入数据库
        user = T_user()
        user.username = username
        user.name = name
        user.email = email
        user.password = password
        user.avatar = '/static/images/m2/avator.png'
        try:
            user.save()
        except:
            result["code"] = -1
            result["text"] = "注册失败，请重新尝试"
    return HttpResponse(json.dumps(result))


# 登录账号
def login_user(request):
    '''

    :param request: username, password
    :return:code:是否登录成功
            text:文本提示
    '''

    result = {
        "code": 0,
        "text": "登录成功"
    }

    # 从请求中获取用户输入登录账号信息
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 进入数据库比对登录账号是否合法
    # print(username,password)
    user_result = T_user.objects.filter(username=username)
    if not user_result.exists():
        result["code"] = -1
        result["text"] = "用户名不存在，请重新输入"
    else:
        if user_result[0].password != password:
            result["code"] = -1
            result["text"] = "密码错误，请重新输入"
        else:
            request.session['logined'] = 1
            # print(request.session.get('logined', 0))
            request.session['user_id'] = user_result[0].id
            request.session['username'] = user_result[0].name
            result['user_id'] = user_result[0].id
    return HttpResponse(json.dumps(result))


# 显示个人信息
def user_detail(request):
    '''

    :param request: user_id
    :return:
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')

        # 查询用户信息
        user_sql = 'select * from user_t_user where id = %d' % user_id
        user_info = {}
        try:
            cursor.execute(user_sql)
            user_info = cursor.fetchall()
            for user_item in user_info:
                user_item['time'] = str(user_item['time'])
                user_item['birthday'] = str(user_item['birthday'])
                birthday = [s for s in user_item['birthday'].split('-')]
                user_item['year'] = birthday[0]
                user_item['month'] = birthday[1]
                user_item['day'] = birthday[2]
        except Exception as e:
            result['status'] = 403
            print('user_detail:', e)
        result['user_info'] = user_info
    else:
        result['status'] = 403
        result['text'] = '请登录'

    mysql_conn.close()

    return HttpResponse(json.dumps(result))


# 更新个人信息
def user_update(request):
    '''

    :param request: user_id
    :return:
    '''

    result = {'status': 200, 'text': "更新成功"}
    user_id = request.session.get('user_id')

    # 获取用户更新信息
    obj = request.FILES.get('avatar')
    username = request.POST.get('username')
    name = request.POST.get('name')
    email = request.POST.get('email')
    year = request.POST.get('date_of_birth_year')
    month = request.POST.get('date_of_birth_month')
    day = request.POST.get('date_of_birth_day')
    sex = request.POST.get('sex')
    remark = request.POST.get('remark')
    birthday = year + '-' + month + '-' + day

    # 获取1头像信息
    obj = request.FILES.get('avatar')
    if obj != None:
        suffix = obj.name.split('.')[-1]

        # 判断存取路径是否存在
        path = os.getcwd()
        if not os.path.exists(path + './static/upload/'):
            os.makedirs(path + './static/upload/')
        file_name = str(user_id) + '.' + suffix
        avatar = '/static/upload/' + file_name

        # 写入服务器文件夹
        print(path + './static/upload/' + file_name)
        with open(path + './static/upload/' + file_name, "wb") as fp:
            for i in obj.chunks():
                fp.write(i)

        # 更新用户信息
        update_user_sql = 'update user_t_user set username="%s", name="%s", avatar="%s", email="%s", birthday="%s", sex="%s", remark="%s" where id=%d' % (
        username, name, avatar, email, birthday, sex, remark, user_id)
    else:
        update_user_sql = 'update user_t_user set username="%s", name="%s", email="%s", birthday="%s", sex="%s", remark="%s" where id=%d' % (
        username, name, email, birthday, sex, remark, user_id)
    try:
        cursor.execute(update_user_sql)
        mysql_conn.commit()
    except:
        result['status'] = 403
        result['text'] = "更新失败，请重试"

    return HttpResponse(json.dumps(result))


# 通知记录
def user_message(request):
    '''

    :param request:user_id
    :return:回复人ID 回复人姓名 回复人头像 回复内容 回复时间
    '''
    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        # 测试用户账号
        # user_id = 265

        # 查询用户历史评论信息
        comment_sql = 'select id, content from user_t_comment where user_id = %d order by time desc' % user_id
        comment_reply_info = []

        user_info = []
        try:
            lock.acquire()
            cursor.execute(comment_sql)
            user_info = cursor.fetchall()
            lock.release()
        except Exception as e:
            print(comment_sql, e)
            result['status'] = 500

        result['text'] = '暂无通知'
        comment_items = {each['id']: each['content']for each in user_info}
        if comment_items:
            # 查询用户被回复信息
            reply_sql = 'select t1.id reply_user_id, t1.name, t1.avatar,t2.reply_id comment_id, t2.content reply_content, t2.time from ' \
                        'user_t_user t1, user_t_comment t2 where t2.reply_id in %s and t1.id = t2.user_id ' \
                        'order by t2.time desc' % repr(tuple(set(comment_items.keys()) | {-3, -4}))

            reply_info = []
            try:
                lock.acquire()
                cursor.execute(reply_sql)
                reply_info = cursor.fetchall()
                lock.release()
            except Exception as e:
                print('user_message', reply_sql, e)
                result['status'] = 500

            if reply_info:
                del result['text']
                for reply_item in reply_info[:10]:
                    reply_item['time'] = str(reply_item['time'])
                    reply_item['content'] = comment_items[reply_item['comment_id']]
                    comment_reply_info.append(reply_item)

        result['comment_reply_info'] = comment_reply_info
    else:
        result['status'] = 403
        result['text'] = '请登录'

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 评论记录
def user_comment(request):
    '''

    :param request: type
    :return: 电影ID 电影名 电影封面URL 评论内容 评论时间
             图片ID 电影名 图片URL 评论内容 评论时间
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        type = request.POST.get('type', 0)
        # 测试用户账号
        # user_id = 265

        # 判断查询电影或图片评论
        if type == 0:
            # 查询用户电影评论信息
            comment_sql = 'select t1.id movie_id, t1.movie_name, t1.url image_url, t2.content, t2.time from ' \
                          'movie_t_movie t1, user_t_comment t2 where t2.media_id = t1.id and t2.type = 0 and ' \
                          't2.user_id = %d order by t2.time desc' % (user_id)
        else:
            # 查询用户图片评论信息
            comment_sql = 'select t1.id picture_id, t1.movie_name, t1.url image_url, t2.content, t2.time from ' \
                          'picture_t_picture t1, user_t_comment t2 where t2.media_id = t1.id and t2.type = 1 and' \
                          ' t2.user_id = %d order by t2.time desc' % (user_id)

        comment_info = {}
        try:
            cursor.execute(comment_sql)
            comment_info = cursor.fetchall()
            for comment_item in comment_info:
                comment_item['time'] = str(comment_item['time'])
        except:
            result['status'] = 403
        result['comment_info'] = comment_info
    else:
        result['status'] = 403

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 点赞记录
def user_parise(request):
    '''

    :param request:
    :return:
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        type = request.GET.get('type', 0)
        # user_id = 292

        # 判断查询电影或图片点赞
        if type == 0:
            # 查询用户电影点赞信息
            parise_sql = 'select t1.* from movie_t_movie t1,user_t_parise t2 where t1.id = t2.media_id and ' \
                         't2.type = 0 and t2.user_id = %d order by t2.time desc' % (user_id)
        else:
            # 查询用户图片点赞信息
            parise_sql = 'select t1.* from picture_t_picture t1, user_t_parise t2 where t1.id = t2.media_id and ' \
                         't2.type = 1 and t2.user_id = %d order by t2.time desc' % (user_id)

        try:
            # lock.acquire()
            cursor.execute(parise_sql)
            result['info'] = cursor.fetchall()
            # lock.release()
        except Exception as e:
            result['status'] = 403
            print('user_parise:', parise_sql, e)

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 收藏记录
def user_star(request):
    '''

    :param request:
    :return:
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        type = request.GET.get('type', 0)
        # user_id = 292

        # 判断查询电影或图片收藏
        if type == 0:
            # 查询用户电影收藏信息
            star_sql = 'select t1.* from movie_t_movie t1,user_t_star t2 where t1.id = t2.media_id and ' \
                       't2.type = 0 and t2.user_id = %d order by t2.time desc' % (user_id)
        else:
            # 查询用户图片收藏信息
            star_sql = 'select t1.* from picture_t_picture t1, user_t_star t2 where t1.id = t2.media_id and ' \
                       't2.type = 1 and t2.user_id = %d order by t2.time desc' % (user_id)
        star_info = {}
        try:
            # lock.acquire()
            cursor.execute(star_sql)
            star_info = cursor.fetchall()
            # lock.release()
        except Exception as e:
            result['status'] = 403
        result['info'] = star_info

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 下载记录
def user_download(request):
    '''

    :param request:
    :return:
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')

        # 查询用户图片下载信息
        download_sql = 'select t1.* from picture_t_picture t1, user_t_download t2 where t1.id = t2.picture_id and ' \
                   't2.user_id = %d order by t2.time desc' % user_id

        try:
            cursor.execute(download_sql)
            result['info']= cursor.fetchall()
        except Exception as e:
            print('user_download:', download_sql, e)
            result['status'] = 403

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 添加评论
def user_new_comment(request):
    '''

    :param request:
    :return:
    '''
    result = {'status': 200, 'text': '评论成功'}
    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        username = request.session.get('username')
        media_id = request.GET.get('media_id')
        content = request.GET.get('content')

        t_comment = T_comment()
        t_comment.user_id = user_id
        t_comment.content = content
        t_comment.media_id = media_id
        t_comment.username = username
        try:
            t_comment.save()
        except:
            result['status'] = 403
            result['text'] = '评论失败，请检查'
    else:
        result['status'] = 403
        result['text'] = '请登录后评论'
    return HttpResponse(json.dumps(result))


# 添加回复
def user_new_reply(request):
    '''

        :param request:
        :return:
        '''
    result = {'status': 200, 'text': '回复成功'}
    # 判断用户是否登录
    logined = request.session.get('logined', 0)
    if logined == 1:
        user_id = request.session.get('user_id')
        username = request.session.get('username')
        media_id = request.GET.get('media_id')
        content = request.GET.get('content')
        reply_id = request.GET.get('reply_id')

        t_reply = T_comment()
        t_reply.user_id = user_id
        t_reply.content = content
        t_reply.media_id = media_id
        t_reply.username = username
        t_reply.reply_id = reply_id
        try:
            t_reply.save()
        except:
            result['status'] = 403
            result['text'] = '回复失败，请检查'
    else:
        result['status'] = 403
        result['text'] = '请登录后回复'
    return HttpResponse(json.dumps(result))


def center(request):
    return render(request, 'center/index.html')


# 获取用户信息
def user_avatar(request):
    result = {'status': 200}
    sql = ''
    try:
        user_id = request.GET.get('user_id')
        sql = "select avatar,name from user_t_user where id = '%s'" % (user_id)
        cursor.execute(sql)
        data = cursor.fetchone()
        result['avatar'] = data['avatar']
        result['name'] = data['name']
    except Exception as e:
        print('user_avatar', sql, e)
        result['status'] = 500
    return HttpResponse(json.dumps(result))


# 判断用户对某部电影，图片是否有过点赞，收藏，评分。
def is_active(request):
    '''

    :param request: movie_id:电影id, user_id:用户id, type:0：电影， 1：图片
    :return: parise:0/1, star:0/1, score:0/评分
    '''
    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    movie_id = request.GET.get('media_id')
    user_id = request.GET.get('user_id')
    type = request.GET.get('type')

    sql_1 = ''
    try:
        sql_1 = "select id from user_t_parise where media_id='%s' and user_id = '%s' and type ='%s'" % (
        movie_id, user_id, type)
        cursor.execute(sql_1)
        data = cursor.fetchone()
        result['parise'] = data
        sql_2 = "select id from user_t_star where media_id='%s' and user_id = '%s' and type ='%s'" % (
        movie_id, user_id, type)
        cursor.execute(sql_2)
        data = cursor.fetchone()
        result['star'] = data
        sql_3 = "select rating from user_t_rating where media_id='%s' and user_id = '%s' and type ='%s'" % (
        movie_id, user_id, type)
        cursor.execute(sql_3)
        data = cursor.fetchone()
        result['rating'] = data
    except:
        print(sql_1)
        result['status'] = 500

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 用户对电影,图片点赞，收藏
def parise_star(request):
    '''

    :param request: user_id:用户id，movie_id:电影id, active:0：点赞，1：收藏， type: 0: 电影, 1：图片
    :return: type: 0:取消点赞，收藏。 1：点赞，收藏成功
    '''
    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    user_id = request.GET.get('user_id')
    media_id = request.GET.get('media_id')
    type = request.GET.get('type')
    active = request.GET.get('active')
    sql = ''
    if active == '0':
        table = 'user_t_parise'
    else:
        table = 'user_t_star'
    try:
        sql = "select id from %s where media_id = '%s' and user_id= '%s' and type='%s'  " % (
        table, media_id, user_id, type)
        cursor.execute(sql)
        data = cursor.fetchall()
        if data:
            sql = "delete from %s where media_id = '%s'and user_id = '%s' and type = '%s'  " % (
            table, media_id, user_id, type)
            type = 0
        else:
            sql = "insert into %s (media_id,user_id,type,time) values('%s','%s','%s',now())" % (
            table, media_id, user_id, type)
            type = 1
        cursor.execute(sql)
        mysql_conn.commit()
        result['type'] = type
    except Exception as e:
        print('parise_star', sql, e)
        result['status'] = 500

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 用户评分
def user_rating(request):
    '''

    :param request: user_id:用户id，movie_id:电影id, type:0：返回用户评分信息，1：用户进行评分操作, rating:用户评分
    :return: 0：rating(用户评分)
    '''

    result = {'status': 200}
    mysql_conn, cursor = ping_mysql()

    user_id = request.GET.get('user_id')
    movie_id = request.GET.get('movie_id')
    type = request.GET.get('type')
    sql = ''
    try:
        sql = "select rating from user_t_rating where media_id = '%s'and user_id= '%s' and type='%d'  " % (
        movie_id, user_id, 0)
        cursor.execute(sql)
        data = cursor.fetchone()
        result['rating'] = data
        if type == '1':
            rating = request.GET.get('rating')
            if not data:
                sql = "insert into user_t_rating (media_id,user_id,rating,type,time) values('%s','%s','%s','%d',now())" % (
                movie_id, user_id, rating, 0)
            else:
                sql = "update user_t_rating set rating = '%s',time=now() where media_id = '%s'and user_id= '%s' and type='%d'  " % (
                rating, movie_id, user_id, 0)
            cursor.execute(sql)
            mysql_conn.commit()
            result['info'] = 1
    except Exception as e:
        print('user_rating:', sql, e)
        result['status'] = 500

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


def log_out(request):
    try:
        del request.session['logined']
        del request.session['username']
        del request.session['user_id']
        return HttpResponse('1')
    except:
        return HttpResponse('0')


# 登录页跳转
def login(request):
    url = request.GET.get('url')
    # print(url)
    return render(request, 'center/login.html', {'url': url})


# 通过sessionid判断用户身份
def session_get(request):
    '''

    :param request: sessionid
    :return: 用户信息
    '''

    result = {'status': 200, 'info': []}
    mysql_conn, cursor = ping_mysql()

    session_key = request.COOKIES.get('sessionid')
    try:
        session = Session.objects.get(session_key=session_key)
        user_id = session.get_decoded().get('user_id')
        sql = "select * from user_t_user where id = '%s'" % user_id
        cursor.execute(sql)
        data = cursor.fetchone()
        data['time'] = str(data['time'])
        data['birthday'] = str(data['birthday'])
        result['info'] = data
    except:
        result = {'status': 500}

    mysql_conn.close()
    return HttpResponse(json.dumps(result))


# 判断是否登录
def isLog(request):
    pass
